package com.none.frontbackend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.none.frontbackend.common.ErrorCode;
import com.none.frontbackend.excption.BusinessException;
import com.none.frontbackend.mapper.UserMapper;
import com.none.frontbackend.model.domain.User;
import com.none.frontbackend.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.none.frontbackend.contant.UserConstant.USER_LOGIN_SATE;

/**
* @author xiaofeng
* @description 针对表【user(user)】的数据库操作Service实现
* @createDate 2025-10-14 23:07:05
*/
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{
    //定义盐值,混淆密码
    private static final String SALT = "";

    @Resource
    private UserMapper userMapper;

    @Override
    public long userRegister(String userAccount, String password, String checkPassword,String planetCode) {
        //校验
        //1.非空
        if(StringUtils.isAnyBlank(userAccount,password,checkPassword,planetCode)) {
           throw new BusinessException(ErrorCode.PARAMS_NULL_ERROR,"参数为空");
        }
        if (planetCode.length() > 5){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户账号过短");
        }
        //2.账号不效于4位，密码不小于8位
        if (userAccount.length() < 4 || password.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户密码过短");
        }
        if (planetCode.length() > 5) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"编号过长");
        }
        //3.不能包含特殊字符
        String regex = "^[a-zA-Z0-9]+$";
        Matcher matcher = Pattern.compile(regex).matcher(userAccount);
        if(!matcher.find()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"不能包含特色字符");
        }

        //4.密码和校验密码相同
        if(!checkPassword.equals(password)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"两次输入密码不同");
        }
        //5.账户不能重复
        //MyBatis-Plus的条件构造器，用于构建SQL查询条件
        QueryWrapper queryWrapper = new QueryWrapper<>();
        //添加查询条件：user_account字段等于指定的userAccount值
        queryWrapper.eq("user_account", userAccount);
        //执行统计查询，返回满足条件的记录数量
        long count = this.count(queryWrapper);
        if(count > 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账号已存在");
        }

        //星球编号不能重复
        //MyBatis-Plus的条件构造器，用于构建SQL查询条件
        queryWrapper = new QueryWrapper<>();
        //添加查询条件：user_account字段等于指定的userAccount值
        queryWrapper.eq("planet_code", planetCode);
        //执行统计查询，返回满足条件的记录数量
        count = this.count(queryWrapper);
        if(count > 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"编号已存在");
        }

        //6. 加密
        //将拼接后的字符串转换为字节数组,解析md5的加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + password).getBytes());
        //7. 插入数据
        User user = new User();
        user.setUsername("test");
        user.setGender(1);
        user.setPhone("123456789");
        user.setPlanetCode(planetCode);
        user.setEmail("test@gmail.com");
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);
        boolean save = this.save(user);
        if(!save) {
            return -1;
        }
        return user.getId();
    }

    @Override
    public User dologin(String userAccount, String password, HttpServletRequest request) {
        //1.非空
        if(StringUtils.isAnyBlank(userAccount,password)) {
            return null;
        }
        //2.账号不效于4位，密码不小于8位
        if (userAccount.length() < 4 || password.length() < 8) {
            return null;
        }
        //3.不能包含特殊字符
        String regex = "^[a-zA-Z0-9]+$";
        Matcher matcher = Pattern.compile(regex).matcher(userAccount);
        if(!matcher.find()) {
            return null;
        }

        //4. 加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + password).getBytes());
        //5. 查询用户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_account", userAccount);
        queryWrapper.eq("user_password",encryptPassword);
        System.out.println(queryWrapper);
        User user = userMapper.selectOne(queryWrapper);
        //用户不存在
        if (user == null){
            log.info("user login faild,userAccount cannt match usrePassword");
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账号密码错误");
        }

        //6. 用户脱敏
        User safetyUser = getSafetyUser(user);
        //7.记录用户的登录状态
        request.getSession().setAttribute(USER_LOGIN_SATE, safetyUser);
        return safetyUser;
    }

    /**
     * 用户脱敏
     * @param originalUser
     * @return
     */
    public User getSafetyUser(User originalUser){
        if (originalUser == null){
            return null;
        }
        User cleanUser = new User();
        cleanUser.setId(originalUser.getId());
        cleanUser.setUsername(originalUser.getUsername());
        cleanUser.setUserAccount(originalUser.getUserAccount());
        cleanUser.setAvatarurl(originalUser.getAvatarurl());
        cleanUser.setGender(originalUser.getGender());
        cleanUser.setPhone(originalUser.getPhone());
        cleanUser.setEmail(originalUser.getEmail());
        cleanUser.setUserStatus(originalUser.getUserStatus());
        cleanUser.setCreateTime(originalUser.getCreateTime());
        cleanUser.setUserRole(originalUser.getUserRole());
        cleanUser.setPlanetCode(originalUser.getPlanetCode());
        return cleanUser;
    }

    /**
     * 用户注销
     * @param request
     */
    @Override
    public int userLginOut(HttpServletRequest request) {
        //移除登录态
        request.getSession().removeAttribute(USER_LOGIN_SATE);
        return 1;
    }
}




